package ro.gateway.aida.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Hashtable;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.Person;
import ro.gateway.aida.obj.db.PersonDB;
import ro.gateway.aida.srv.EditorServlet;
import ro.gateway.aida.srv.ICFService;
import ro.gateway.aida.srv.IIDGenerator;
import ro.gateway.aida.usr.User;
import ro.gateway.aida.usr.UserUtils;
import ro.gateway.aida.utils.HttpUtils;



public class EditPersonServlet
      extends EditorServlet
{
      public EditPersonServlet()
      {
      }

      protected void edit( HttpServletRequest request, HttpServletResponse response ) throws
            javax.servlet.ServletException, java.io.IOException
      {
            request.setAttribute( PNAME_SCREEN, PV_SCR_EDIT );
            request.getRequestDispatcher( JSP_PAGE ).
                  forward( request, response );
      }

      protected void other_action_performed( HttpServletRequest request,
                                             HttpServletResponse response,
                                             String action ) throws javax.servlet.
            ServletException, java.io.IOException
      {
      }

      protected void confirm( HttpServletRequest request,
                              HttpServletResponse response ) throws javax.servlet.
            ServletException, java.io.IOException
      {

            Hashtable bean = ( Hashtable ) request.getAttribute( PNAME_BEAN );
            Person item = ( Person ) bean.get( PNAME_PERS );
            User user = UserUtils.getLogged( request, response );
            if ( user == null ) return;

            if ( item.getUserID() == -1 ) item.setUserID( user.getId() );
            item.setFirstNames( HttpUtils.getValidTrimedString( request, "firstnames", null ) );
            item.setLastName( HttpUtils.getValidTrimedString( request, "lastname", null ) );
            item.setDepartment( HttpUtils.getValidTrimedString( request, "department", null ) );
            item.setState( HttpUtils.getValidTrimedString( request, "state", null ) );
            item.setAddress( HttpUtils.getValidTrimedString( request, "address", null ) );
            item.setPostalCode( HttpUtils.getValidTrimedString( request, "postalcode", null ) );
            
            item.setPhone( HttpUtils.getValidTrimedString( request, "phone1", "" )+ "#" + 
            		HttpUtils.getValidTrimedString( request, "phone2", "" ) + "#" +
					HttpUtils.getValidTrimedString( request, "phone3", "" ));
            
            item.setFax( HttpUtils.getValidTrimedString( request, "fax1", "" )+ "#" + 
            		HttpUtils.getValidTrimedString( request, "fax2", "" ) + "#" +
					HttpUtils.getValidTrimedString( request, "fax3", "" ));
            
        
            item.setEmail( HttpUtils.getValidTrimedString( request, "email", "" ).trim() );
            item.setURL( HttpUtils.getValidTrimedString( request, "URL", null ) );
            item.setCountryISO3( HttpUtils.getValidTrimedString( request, "countryISO3", null ) );

//    item.setID(HttpUtils.getLong(request, "persid", -1));

            request.setAttribute( PNAME_SCREEN, PV_SCR_CONFIRM );
            request.getRequestDispatcher( JSP_PAGE ).
                  forward( request, response );
      }

      protected void start_editing(
            ServletContext application,
            HttpServletRequest request,
            HttpServletResponse response ) throws IOException, ServletException
      {
            super.start_editing( application, request, response );
			PersistenceToken token = PersistenceManager.tokenLookup( application );
            HttpSession session = request.getSession();
            Hashtable beans = ( Hashtable ) session.getAttribute( PNAME_BEANS );
            Hashtable bean = ( Hashtable ) request.getAttribute( PNAME_BEAN );

            String action = ( String ) bean.get( PNAME_ACTION );
            String key = ( String ) request.getAttribute( PNAME_KEY );

            if ( PV_ACTION_EDIT.equals( action ) || PV_ACTION_DELETE.equals( action ) )
            {
                  ICFService cfService = ( ICFService ) ( ( Hashtable ) application.
                        getAttribute( Constants.SERVICES ) ).
                        get( Constants.SERVICE_CF );

                  long persid = HttpUtils.getLong( request, "persid", -1 );

                  Person pers = null;
                  try
                  {
                        PersonDB persdb = PersonDB.getManager(token);
                        pers = persdb.getByID( persid );
                  }
                  catch ( SQLException e )
                  {
                        e.printStackTrace();
                        request.setAttribute( PNAME_SCREEN, PV_SCR_ERROR );
                        request.setAttribute( PNAME_ERRORS, "User not found" );
                        request.getRequestDispatcher( JSP_PAGE ).
                              forward( request, response );
                        return;
                  }
                  if ( pers == null )
                  {
                        pers = new Person();
                        pers.setId( persid );
                  }


                  bean.put( PNAME_PERS, pers );
                  bean.put( PNAME_ACTION, action );
            }
            else if ( PV_ACTION_NEW.equals( action ) )
            {
                  Person pers = new Person();
                  bean.put( PNAME_PERS, pers );
            }
            else
            {
                  beans.remove( key );
                  response.sendError( HttpServletResponse.SC_NOT_FOUND );
                  return;
            }
      }

      public String getPNAME_BEANS()
      {
            return PNAME_BEANS;
      }

      protected void cancel(
            HttpServletRequest request,
            HttpServletResponse response ) throws IOException, ServletException
      {
            super.cancel( request, response );
      }

      protected void save( ServletContext application, HttpServletRequest request,
                           HttpServletResponse response ) throws javax.servlet.
            ServletException, java.io.IOException
      {
			PersistenceToken token = PersistenceManager.tokenLookup( application );
            Hashtable bean = ( Hashtable ) request.getAttribute( PNAME_BEAN );
            Hashtable beans = ( Hashtable ) request.getSession().getAttribute( PNAME_BEANS );
            Person pers = ( Person ) bean.get( PNAME_PERS );
            String action = ( String ) bean.get( PNAME_ACTION );
            String[] errors = null;

            ICFService cfService = ( ICFService ) ( ( Hashtable ) application.
                  getAttribute( Constants.SERVICES ) ).get(
                        Constants.SERVICE_CF );
            IIDGenerator idGenerators = ( IIDGenerator ) ( ( Hashtable ) application.
                  getAttribute( Constants.SERVICES ) ).
                  get( Constants.SERVICE_IDGEN );

            try
            {
                  PersonDB persdb = PersonDB.getManager(token);
                  if ( PV_ACTION_DELETE.equals( action ) )
                  {	
                        persdb.delete( pers.getId() );
					    response.sendRedirect(request.getContextPath()+"/viewpers.do");
					    return;
                  }
                  else if ( PV_ACTION_NEW.equals( action ) )
                  {
                        persdb.insert( idGenerators, pers );
                  }
                  else
                  {
                        persdb.update( pers );
                  }
            }
            catch ( SQLException e )
            {
                  errors = new String[]{
                        e.getMessage()};
            }

            if ( errors == null )
            {
                  beans.remove( bean.get( PNAME_KEY ) );
                  response.sendRedirect( ( String ) bean.get( PNAME_REFERER ) );
                  return;
            }
            else
            {
                  request.setAttribute( PNAME_SCREEN, PV_SCR_ERROR );
                  request.setAttribute( PNAME_ERRORS, errors );
                  request.getRequestDispatcher( JSP_PAGE ).
                        forward( request, response );
                  return;
            }

      }

      public String getJSP_PAGE()
      {
            return JSP_PAGE;
      }

      public static final String PNAME_BEANS = "EDITING_PERSONS";
      public static final String PNAME_PERS = "PERS";
      public static final String JSP_PAGE = "persoane.jsp";
      public static final String PNAME_ERRORS = "errors";

}
